package listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class OnlineUser implements ServletContextListener,
  HttpSessionListener, HttpSessionAttributeListener {

  private static int userNum = 0;
  // Public constructor is required by servlet spec
  public OnlineUser() {
  }

  // -------------------------------------------------------
  // ServletContextListener implementation
  // -------------------------------------------------------
  public void contextInitialized(ServletContextEvent sce) {
      /* This method is called when the servlet context is
         initialized(when the Web application is deployed). 
         You can initialize servlet context related data here.
      */
  }

  public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
  }

  // -------------------------------------------------------
  // HttpSessionListener implementation
  // -------------------------------------------------------
  public void sessionCreated(HttpSessionEvent se) {
      /* Session is created. */
    ++userNum;
    System.out.println("new user, total " + userNum);
  }

  public void sessionDestroyed(HttpSessionEvent se) {
      /* Session is destroyed. */
    --userNum;
    System.out.println("user offline, total" + userNum);
  }

  public static int getOnlineUser() {
    return userNum;
  }

  // -------------------------------------------------------
  // HttpSessionAttributeListener implementation
  // -------------------------------------------------------

  public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
    System.out.println(sbe.getName()); // 添加的属性键名
    System.out.println(sbe.getValue()); // 添加的属性值
    System.out.println(sbe.getSession()); // 当前session
  }

  public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    System.out.println(sbe.getName()); // 添加的属性键名
    System.out.println(sbe.getValue()); // 添加的属性值
    System.out.println(sbe.getSession()); // 当前session
  }

  public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attibute
         is replaced in a session.
      */
  }
}
